package com.itheima.singleton.demo8;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author zzw
 */
public class Test {
    public static void main(String[] args) throws Exception {
        writeObjectToFile();
        //从文件中读取对象
        Singleton s1 = readObjectFromFile();
        Singleton s2 = readObjectFromFile();

        //判断两个反序列化后的对象是否是同一个对象
        System.out.println(s1 == s2);
    }

    private static Singleton readObjectFromFile() throws Exception {
        //创建对象输入流对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("E:\\a.txt"));
        //第一个读取Singleton对象
        return (Singleton) ois.readObject();
    }

    // 序列化示例代码（需要在读取之前执行一次）
    private static void writeObjectToFile() throws Exception {
        Singleton instance = Singleton.getInstance();
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:\\a.txt"));
        oos.writeObject(instance);
        oos.close();
    }
}